import React, {Component} from "react";
import {Switch} from 'antd';


import {
    Form,
    Input,
    Table,
    Modal,
    message,
    Row,
    Button,
    Col,
    Select,
} from "antd";


const {confirm} = Modal;
const {Search} = Input;
const {Option} = Select;

import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined
} from "@ant-design/icons";

import axios from "@src/lib/axios";
import "@src/style/tableCom.scss";
import PageTitle from "@src/components/PageTitle";


export default class User extends Component {
    formRef = React.createRef();
    editFormRef = React.createRef();
    state = {
        params: {
            nick_name: "",
            page: 1,
            size: 15,
            is_enable: "",
        },
        visible: false,
        userList: [],
        total: 0,
        loading: false,
        rowId: 0,
        visibleEdit: false,
        editId:"",
    };

    fetchData = () => {
        const {params} = this.state;
        axios.post("/supplier/user/list", params).then(res => {
            if (res.code === 0) {
                let data = res.data;
                this.setState({
                    userList: data.list,
                    total: data.total
                });
            }
        });
    };
    // 在render方法执行前被调用
    UNSAFE_componentWillMount() {
        this.fetchData();
    }

    onValuesChange = (changedValues, allValues) => {
        console.log(changedValues, allValues);
        Object.assign(this.state.params, {...changedValues});
        this.fetchData();
    };

    onChangePage = (page) => {
        this.state.params.page = page;

    };
    showConfirm = (id, checked, nickName) => {
        const that = this;
        confirm({
            title: `是否${checked==1 ? '启用' : '禁用'}${nickName}?`,
            content: '',
            okText: '确认',
            cancelText: '取消',
            style: {padding: '32px 20px'},
            onOk() {
                that.onChange(id, checked);
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    };

    showModal = () => {
        this.setState({
            visible: true,
        });

    };
    handleOk = (e) => {
        let data = this.formRef.current.getFieldsValue();
        axios.post("/supplier/user/add", data).then(res => {
            if (res.code === 0) {
                this.setState({visible: false});
                this.formRef.current.resetFields();
                message.success("添加成功");
                this.fetchData();
            } else {
                message.error(res.msg);
            }
        });
    };


    handleCancel = e => {
        this.formRef.current.resetFields();
        this.setState({
            visible: false,
        });
    };

    onSearchHandler = nick_name => {
        Object.assign(this.state.params, {nick_name});
        this.fetchData();
    };

    //显示编辑弹窗
    toEditShowModal = (row) => {
        let id = row.id;
        axios.post("/supplier/user/user_info",{id}).then(res => {
            if (res.code === 0) {
                let data = res.data;
                this.setState({
                    visibleEdit: true,
                    editId:id
                });
                this.editFormRef.current.setFieldsValue(data);
            }else{
                message.error(res.msg)
            }
        });
    };
    //点击确定
    toEditHandleOk = (e) => {
        let data = this.editFormRef.current.getFieldsValue();
        Object.assign(data,{"id":this.state.editId});
        axios.post("/supplier/user/edit",data).then(res=>{
            if (res.code === 0) {
                this.editFormRef.current.resetFields();
                this.setState({
                    visibleEdit: false,
                    editId:"",
                });
                message.success(res.msg)
                this.fetchData();
            }else {
                message.error(res.msg)
            }
        });
    };
    //点击取消
    toEditHandleCancel = (e) => {
        this.setState({
            visibleEdit: false,
            editId:""
        });
    };


    onChange = (id, enable) => {
        //请求接口修改数据
        axios.post("/supplier/user/switch", {id, enable}).then(res => {
            if (res.code === 0) {
                message.success("修改成功");
                this.fetchData();
            }
        });
    };

    deleteUser = (id)=>{
        const that = this;
        confirm({
            title:"是否确认删除该用户",
            content:'',
            okText: "确认",
            cancelText: "取消",
            style:{padding: '32px 20px'},
            onOk() {
                that.delUser(id);
            },
            onCancel(){
                console.log('Cancel delete');
            }
        });
    };

    delUser = (id) => {
        axios.post("/supplier/user/del",{id}).then(res=>{
            if (res.code === 0) {
                message.success(res.msg)
            }else{
                message.error(res.msg)
            }
            this.fetchData()

        });
    };



    render() {
        let {params, userList, total} = this.state;
        const userColumns = [
            {
                title: "ID",
                width: 20,
                dataIndex: "id",
                align: "center",
            },
            {
                title: "账号",
                width:20,
                dataIndex:"username",
                align:"center,"
            },
            {
                title: "姓名",
                width: 80,
                dataIndex: "nick_name",
                align: "center"
            },
            {
                title: "状态",
                key: "is_enable",
                width: 80,
                dataIndex: "is_enable",
                align: "center",
                render: (text, record) => (
                    <Switch checkedChildren="启用" unCheckedChildren="禁用"
                            onChange={() => this.showConfirm(record.id, record.is_enable == 1 ? 2 : 1, record.nick_name)}
                            checked={text == 1 ? true : false} key={record.id}
                    />
                )
            },
            {
                title: "手机号",
                width: 80,
                dataIndex: "mobile",
                align: "center"
            },
            {
                title: "操作",
                width: 80,
                dataIndex: "id",
                align: "center",
                render: (e, row, index) => (
                    <div>
                        <Button type="link" onClick={() => this.toEditShowModal(row)}>
                            <EditOutlined/>编辑
                        </Button>
                        <Button type="link" onClick={() => this.deleteUser(row.id)}>
                            <DeleteOutlined />删除
                        </Button>


                        <Modal
                            title="编辑员工信息"
                            visible={this.state.visibleEdit}
                            onOk={this.toEditHandleOk}
                            onCancel={this.toEditHandleCancel}
                            maskClosable
                            maskStyle={{backgroundColor: 'rgba(0,0,0,.15)'}}
                        >
                            <Form
                                ref={this.editFormRef}>
                                <Form.Item
                                    label="手机号"
                                    name="mobile"
                                    rules={[
                                        {required: true, message: "填写手机号!"},
                                        {len: 11, message: "请你填写正确的手机号"}
                                    ]}
                                >
                                    <Input placeholder="手机号"/>
                                </Form.Item>
                                <Form.Item
                                    label="姓名"
                                    name="nick_name"
                                    rules={[
                                        {required: true, message: "填写姓名!"}
                                    ]}
                                >
                                    <Input placeholder="请填写员工姓名" style={{width: '100%'}}/>
                                </Form.Item>
                            </Form>


                        </Modal>
                    </div>
                )
            }

        ];

        return (
            <div style={{padding: "0 15px 100px 15px", background: "#fff"}}>
                <PageTitle title="员工列表"/>
                <Row style={{padding: "20px 0 0 0 "}}>
                    <Col span={24}>
                        <Form
                            size="small"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 24}}
                            name="basic"
                            initialValues={params}
                            onValuesChange={this.onValuesChange}>
                            <Row gutter={20}>
                                <Col span={3}>
                                    <Form.Item label="状态" colon={false} name="is_enable" >
                                        <Select>
                                            <Option value={''}>全部</Option>
                                            {/*<Option  value={0}>全部</Option>*/}
                                            <Option  value={1}>启用</Option>
                                            <Option  value={2}>禁用</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col span={5}>
                                    <Button type="primary" onClick={this.showModal}>
                                        <PlusOutlined/>添加员工
                                    </Button>
                                    <Modal

                                        title="添加员工"
                                        visible={this.state.visible}
                                        onOk={this.handleOk}
                                        onCancel={this.handleCancel}
                                    >
                                        <Form
                                            ref={this.formRef}
                                        >
                                            <Form.Item
                                                label="账号"
                                                name="username"
                                                rules={[{required: true, message: '请填写账号!',}, {
                                                    min: 6,
                                                    'message': "用户名必须大于6位长度"
                                                }
                                                    , {max: 25, 'message': "用户名长度不能超过25个字符"}
                                                    , {whitespace: true, message: "用户名不能有空格"}
                                                ]}
                                                hasFeedback>
                                                <Input placeholder="用户名" style={{width: '100%'}}/>
                                            </Form.Item>

                                            <Form.Item label="密码" name="password"
                                                       rules={[{required: true, message: '请填写密码!',}]}
                                                       hasFeedback>
                                                <Input.Password placeholder="密码" style={{width: '100%'}}/>
                                            </Form.Item>

                                            <Form.Item
                                                label="确认密码"
                                                name="confirm"
                                                dependencies={['password']}
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '请填写密码!',
                                                    },
                                                    ({getFieldValue}) => ({
                                                        validator(rule, value) {
                                                            if (!value || getFieldValue('password') === value) {
                                                                return Promise.resolve();
                                                            }
                                                            return Promise.reject('密码输入有误,请确认填写的密码是否相同');
                                                        },
                                                    })

                                                ]}
                                            >
                                                <Input.Password placeholder="确认密码" style={{width: '100%'}}/>
                                            </Form.Item>
                                            <Form.Item
                                                label="手机号"
                                                name="mobile"
                                                rules={[
                                                    {required: true, message: "填写手机号!"},
                                                    {len: 11, message: "请你填写正确的手机号"}
                                                ]}
                                            >
                                                <Input placeholder="手机号"/>
                                            </Form.Item>
                                            <Form.Item
                                                label="姓名"
                                                name="nick_name"
                                                rules={[
                                                    {required: true, message: "填写姓名!"}
                                                ]}
                                            >
                                                <Input placeholder="请填写员工姓名" style={{width: '100%'}}/>
                                            </Form.Item>


                                        </Form>
                                    </Modal>
                                </Col>
                                <Col span={14} align="right" style={{padding: "0 20px 0 0"}}>
                                    <Search
                                        style={{width: "200px"}}
                                        placeholder="输入员工姓名"
                                        onSearch={value => this.onSearchHandler(value)}
                                        enterButton
                                    />
                                </Col>
                            </Row>


                        </Form>
                    </Col>
                </Row>
                <Table
                    size="small"
                    columns={userColumns}
                    rowKey="id"
                    dataSource={userList}
                    pagination={{
                        total,
                        pageSize: 15,
                        current: this.state.params.page,
                        onChange: this.onChangePage,
                        hideOnSinglePage: true
                    }}
                />
            </div>
        );
    }
}
